package com.ictech.print.job;

import android.content.ContentValues;
import android.content.Context;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.util.LinkedList;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import org.json.JSONObject;

import com.ictech.print.BaseApplication;
import com.ictech.print.entity.PrintJobBean;
import com.ictech.print.event.JsEvent;
import com.ictech.print.service.PrinterService;
import com.ictech.print.ui.MainActivity;
import com.ictech.print.utils.FileUtil;
import com.ictech.print.utils.HttpUtils;
import com.ictech.print.utils.JsonUtil;


public class PrintJob extends Thread {

	private final int noContent = 0x00;
	private final int gettingContent = 0x01;
	private final int printContent = 0x02;
	private final int printError = 0x03;
	private final int printSuccess = 0x04;
	private final int contentEmpty = 0x05;

	/*通过MethodAgent类来使用打印服务中的方法*/
	public static PrinterService.MethodAgent mPrinterMethodAgent;


	public static PrintJob instance = new PrintJob();
	
	private LinkedList<PrintJobBean> jobids = new LinkedList<PrintJobBean>();
	
	public static PrintJob get() {
		return instance;
	}
	
	private PrintJob() {
		this.start();
	}

	private android.os.Handler printJobHandler = new android.os.Handler(){
		@Override
		public void handleMessage(Message msg) {
			Context ctx = BaseApplication.app;
			super.handleMessage(msg);
			switch (msg.what) {
				case noContent:{
//					Toast.makeText(ctx, "没有打印记录", Toast.LENGTH_SHORT).show();
				}break;
				case gettingContent:{
					Toast.makeText(ctx, "正在处理中...", Toast.LENGTH_SHORT).show();
				}break;
				case printContent:{
					Toast.makeText(ctx, "正在打印中...", Toast.LENGTH_LONG).show();
				}break;
				case printError:{
					Toast.makeText(ctx, "打印失败", Toast.LENGTH_LONG).show();
				}break;
                case printSuccess:{
                    Toast.makeText(ctx, "打印成功", Toast.LENGTH_LONG).show();
                }break;
                case contentEmpty:{
                    Toast.makeText(ctx, "内容为空", Toast.LENGTH_LONG).show();
                }break;
				default:
					break;
			}
		}
	};

	public synchronized void addJob(String jobid) {
		if (jobid == null || jobid.length() == 0) {
			return;
		}
		PrintJobBean printJobBean = new PrintJobBean();
		printJobBean.eid = FileUtil.getEid();
		printJobBean.jobid = jobid;
		jobids.addLast(printJobBean);
	}
	
	public synchronized PrintJobBean getJob() {
		if (jobids.isEmpty()) {
			return null;
		}
		return jobids.getFirst();
	}
	
	public synchronized void removeJob() {
		if (!jobids.isEmpty()) {
			jobids.removeFirst();
		}
		JsEvent.post("showTraceableCode()");
	}

	@Override
	public void run() {
		for (;;) {
			try {
				PrintJobBean printJobBean = getJob();
				if (printJobBean != null) {
					if (printJobBean.isExpire()) {
						removeJob();
						continue;
					}
					String eid = printJobBean.eid;
					String printData = getPrintData(eid, printJobBean.jobid);
					if (printData != null && printData.length() > 0) {
						try {
							JSONObject json = new JSONObject(printData);
							if (JsonUtil.getInt(json, "print_f", 0) == 0) {
								//没有打印数据
								Log.i("打印测试", "没有打印数据");
                                Log.i("打印测试", "printData为：" + printData);
//								Message msg = new Message();
//								msg.what = noContent;
//								printJobHandler.sendMessage(msg);

							} else if (JsonUtil.getInt(json, "print_f", 0) == 1) {
								//正在处理
							    Log.i("打印测试", "正在处理..");
                                Log.i("打印测试", "printData为：" + printData);
								Message gettingContentMsg = new Message();
                                gettingContentMsg.what = gettingContent;
								printJobHandler.sendMessage(gettingContentMsg);
							} else if (JsonUtil.getInt(json, "print_f", 0) == 2) {
							    // 存在打印数据
								Log.i("打印测试", "存在打印数据");
                                Log.i("打印测试", "printData为：" + printData);
								String content = JsonUtil.getString(json, "content", "");
								//Log.i("打印测试", "打印内容为：" + content);
								if (content != null && content.length() > 0 && !content.equals("[]")) {
									Message printContentMsg = new Message();
									printContentMsg.what = printContent;
									printJobHandler.sendMessage(printContentMsg);
									/*使用打印机打印文本*/
									if (mPrinterMethodAgent != null) {
										if (mPrinterMethodAgent.printBill(content)){
                                            //打印成功
											Log.i("打印测试", "打印成功");
                                            Message printSuccessMsg = new Message();
											printSuccessMsg.what = printSuccess;
                                            printJobHandler.sendMessage(printSuccessMsg);
										}else {
											//打印失败
											Log.i("打印测试", "打印失败");
											Message printErrorMsg = new Message();
											printErrorMsg.what = printError;
											printJobHandler.sendMessage(printErrorMsg);
										}
									}else {
										//打印机离线
//                                        Log.i("打印测试", "打印机离线");
									}
//									printFinish(eid, printJobBean.jobid);
								}else {
                                    //打印内容为空
                                    Log.i("打印测试", "打印内容为空");
                                    Message contentEmptyMsg = new Message();
                                    contentEmptyMsg.what = contentEmpty;
                                    printJobHandler.sendMessage(contentEmptyMsg);
                                }
                                printFinish(eid, printJobBean.jobid);
								removeJob();
							}
						} catch (Exception e) {
						}
					}
				}
			} catch (Exception e) {
			}
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
			}
		}
	}
	
	public String getPrintData(String eid, String jobid) {
		String printjobUrl = "https://gw.ieasybuy.cn/printjob?eid=" + eid + "&jobid=" + jobid;
		String printData = HttpUtils.getInstance().get(printjobUrl);
		return printData;
	}
	
	/**
	 * 上报完成打印
	 * @param eid
	 * @param jobid
	 */
	public void printFinish(String eid, String jobid) {
		String url = "https://gw.ieasybuy.cn/printjob_confirm?eid=" + eid + "&jobid=" + jobid;
		//String url = "https://gw.ieasybuy.cn/printjob_confirm?eid=2042170200017" +"&jobid=" + jobid;
		HttpUtils.getInstance().get(url);
	}
	
}
